package com.filldream.sun.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.filldream.sun.bean.chAddress.ChAddress;
import com.filldream.sun.bean.chAddress.Districts;

/**
 * 省市区工具类
 * @author RickSun
 *
 */
public class ChAddressUtil {

	/**
	 * 根据指定地区获取下级地区
	 * @param name 行政地区名称
	 * @param level  需要获取的行政等级 1-所有省 2-市 3-区
	 * @return
	 * example:
	 * 	name:浙江省/null level:0   结果：所有省
	 * 	name:浙江省 level:2   结果：浙江省的所有市
	 * 	name:杭州市 level:3   结果：杭州市的所有区
	 */
	public static List<ChAddress> getLowerCity(String name,Integer level){
		String jsonText = FileIOUtil.fileToString("/file/area2.txt");
		List<ChAddress> chAddressList = JsonUtil.fromJosnArray(jsonText,ChAddress.class);
		List<ChAddress> resultList = new ArrayList<>();

		//获取省
		if(level == 1){
			return chAddressList;
		}else if(level == 2){
			for(ChAddress chAddress : chAddressList){
				//市级列表
				List<Districts> districtsList = chAddress.getDistricts();
				for(Districts district : districtsList){
					if( name.indexOf(chAddress.getName()) >= 0 ){
						chAddress.setDistricts(Arrays.asList(district));
						resultList.add(chAddress);
						return resultList;
					}else if( !SunCommon.isBlank(district.getFullname()) &&  name.indexOf(district.getFullname()) >= 0){
						chAddress.setDistricts(Arrays.asList(district));
						resultList.add(chAddress);
						return resultList;
					}
				}
			}
		}else if(level == 3){
			for(ChAddress chAddress : chAddressList){
				//市级列表
				List<Districts> districtsList = chAddress.getDistricts();
				//市
				for(Districts district : districtsList){
					//区列表
					List<Districts> districts = district.getDistricts();
					if( name.indexOf(district.getName()) >= 0 ){
						ChAddress result = new ChAddress();
						result.setName(district.getFullname());
						result.setDistricts(districts);
						result.setLevel("city");
						result.setAdcode(district.getAdcode());
						resultList.add(result);
						return resultList;
					}

				}
			}
		}
		return Collections.emptyList();
	}
}
